var wxParse = require('../../wxParse/wxParse.js');
var common = require("../../utils/Conmon.js");
var app = getApp();
var custId = app.globalData.custID;
var apiurl = app.globalData.apiurl;
var selectIndex = []
var num = 1;
var Status = 0;
var PageIndex = 1;
var PageSize = 5;
var IsLastPage = false;

var goodsinfoList = [];
var goodsinfo = null;
Page({
  data: {
    array: ['参数1', '参数2'],
    cansu: false,
    index: 0,
    like: false,
    tab: [
      { id: "0", text: "商品详情", selected: true },
      { id: "1", text: "商品评价", selected: false },
    ],
    imgUrls: [],
    indicatorDots: true,
    autoplay: true,
    interval: 5000,
    duration: 500,
    popin: false,
    sharepopin: false,
    selected: true,
    selected1: false,
    productId: 0,
    vo: [],
    specList: [],
    num: num,
    _spechtml: "",
    goodsinfo: null,
    shopID: 0,
    CommentList: [],
    storeHide: true,
    shopName: "",
    Logo: "",
    StockNum: 0,
    SurplusStockNum: 0,
    CollectionNum: 0
  },


  bindPickerChange: function (e) {
    // console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      index: e.detail.value
    })
  },
  //收藏
  changlike: function () {
    collect(this);
  },
  changetab: function (e) {
    var id = e.currentTarget.id;
    var tab = this.data.tab;
    var len = tab.length;
    for (var i = 0; i < len; i++) {
      if (tab[i].id == id) {
        if (id == 1 && PageIndex == 1) {
          QueryCommentList(this);
        }
        tab[i].selected = true;
      } else {
        tab[i].selected = false;
      }
    }
    this.setData({
      tab: tab
    });
  },
  cansuPop: function () {
    this.setData({
      cansu: !this.data.cansu
    });
  },
  sharePop: function () {
    this.setData({
      sharepopin: !this.data.sharepopin
    });
  },
  selectGg: function (e) {
    this.setData({
      popin: !this.data.popin
    });
  },
  onLoad: function (options) {
    common.pageInit( function () { });
    var shopID = 0;
    var storeHide = true;
    if (options.shopID > 0) {
      shopID = options.shopID;
      storeHide = false;
    }
    this.setData({
      productId: options.productId,
      shopID: shopID,
      storeHide: storeHide
    });
    loadDetail(this);
    if (shopID > 0) {
      loadUnionStore(this);
    }
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    wx.stopPullDownRefresh();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if (this.data.tab[1].selected) {
      if (IsLastPage) {
        wx.showToast({
          title: '已到底',
          duration: 2000
        })
        return false;
      }
      ++PageIndex;
      QueryCommentList(this);
    }
  },

  //减少数量
  onsub: function (e) {
    num--;
    if (num < 1) {
      num = 1;
    }
    this.setData({
      num: num
    })
  },
  //增加数量
  onplus: function (e) {
    num++;
    this.setData({
      num: num
    })
  },
  onblur: function (e) {
    num = e.detail.value;
    if (num < 1) {
      num = 1;
    }
    this.setData({
      num: num
    })
  },
  //选择规格
  onselectspec: function (e) {
    var that = this;
    var id = e.currentTarget.id, pid = e.currentTarget.dataset.pid, list = that.data.specList;
    selectIndex[pid] = id

    var arr = [];
    for (var i = 0, len = selectIndex.length; i < len; ++i) {
      if (selectIndex[i])
        arr.push(selectIndex[i]);
    }
    var _specIds = arr.join(',');
    for (var i = 0, len = goodsinfoList.length; i < len; ++i) {
      if (goodsinfoList[i].SpecID == _specIds) {
        goodsinfo = goodsinfoList[i];
      }
    }

    var _specArr = [];
    for (var i = 0, len = list.length; i < len; ++i) {
      for (var j = 0, length = list[i].length; j < length; ++j) {
        if (list[i][j].ParentID == pid && list[i][j].ID != id) {
          list[i][j].IsChecked = false;
        }
        if (list[i][j].ID == id) {
          list[i][j].IsChecked = true;
        }
        for (var k = 0, len2 = arr.length; k < len2; ++k) {
          if (arr[k] == list[i][j].ID) {
            _specArr.push(list[i][j].SpecValue);
          }
        }
      }
    }
    that.setData({
      specList: list,
      _spechtml: _specArr.join('-'),
      goodsinfo: goodsinfo
    })
  },
  //加入购物车
  addtocart: function (e) {
    if (!goodsinfo || goodsinfo == undefined) {
      wx.showModal({
        content: "请选择规格",
        showCancel: false,
        confirmText: "确定"
      })
      return;
    }
    if (num <= 0 || num > goodsinfo.StockNum) {
      wx.showModal({
        content: "库存不足",
        showCancel: false,
        confirmText: "确定"
      })
      return;
    }
    var data = {
      ProductID: goodsinfo.ProductID,
      BuyNum: num,
      GoodsID: goodsinfo.GoodsID,
      CustID: custId,
      UserID: wx.getStorageSync('UserInfo').UserID,
      ShopId: this.data.shopID
    };
    var that = this;
    var typeid = e.currentTarget.dataset.type;
    var url = app.globalData.apiurl + "/mobile/api/ShopCart/InsertShopCart";
    if (typeid == 1) {  //立即购买
      url = app.globalData.apiurl + '/mobile/api/ShopCart/BuyNow';
    }
    wx.request({
      url: url,
      data: JSON.stringify(data),
      method: 'POST',
      header: {
        'X_ManuName': app.globalData.manuName
      },
      success: function (res) {
        if (res.data.code == 1200) {
          if (typeid == 1) {  //立即购买
            var cart = res.data.content;
            if (cart) {
              var clist = [];
              clist.push(cart);
              //将购物车选中项缓存起来
              wx.setStorageSync('Winmobi4MallSelectedShopCart', clist);
              wx.navigateTo({
                url: '/pages/submitOrder/submitOrder'
              })
            } else {
              wx.showModal({
                content: '操作失败',
                showCancel: false,
                confirmText: "确定"
              })
            }
          } else {
            that.setData({
              popin: false
            });
            wx.showToast({
              title: '操作成功',
              icon: 'success',
              duration: 2000
            })
          }
        } else {
          wx.showModal({
            content: res.data.msg,
            showCancel: false,
            confirmText: "确定"
          })
        }
      }
    })
  },
  //购物车
  gocart: function (e) {
    wx.switchTab({
      url: '/pages/cart/cart'
    })
  }
})
//加载数据
function loadDetail(that) {
  wx.showLoading({
    title: '加载中...',
    mask: true
  });
  wx.request({
    url: app.globalData.apiurl + '/mobile/api/Product/GetProductDetail',
    data: { custId: custId, productId: that.data.productId, userId: wx.getStorageSync('UserInfo').UserID, unionShopID: that.data.shopID },
    method: 'GET',
    header: {
      'X_ManuName': app.globalData.manuName
    },
    success: function (res) {
      //wx.hideToast();
      wx.hideLoading();
      if (res.data.code == 1200) {
        var result = res.data.content;
        goodsinfoList = result.GoodsInfoList;
        selectIndex = [];
        goodsinfo = null;
        var like = false;
        if (result.Like) {
          like = true;
        }
        if (result.ProductDetail.Detail) {
          wxParse.wxParse('content', 'html', result.ProductDetail.Detail, that, 5)
        }
        if (result.ProductDetail.Parameter) {
          wxParse.wxParse('content2', 'html', result.ProductDetail.Parameter, that, 5)
        }
        that.setData({
          vo: result,
          specList: result.SpecList,
          imgUrls: result.ProductInfo.ProductImgList,
          like: like
        });
      } else {
        console.log('加载失败');
      }
    }
  })
}

//收藏
function collect(that) {
  var data =
    {
      CustID: custId,
      UserID: wx.getStorageSync('UserInfo').UserID,
      ProductID: that.data.productId,
      UnionShopID: that.data.shopID
    };
  var collectUrl = "";
  if (that.data.like) {
    collectUrl = app.globalData.apiurl + "/mobile/api/Collection/CancelCollection";
  } else {
    collectUrl = app.globalData.apiurl + "/mobile/api/Collection/InsertMemberCollection";
  }
  wx.request({
    url: collectUrl,
    data: JSON.stringify(data),
    method: 'POST',
    header: {
      'X_ManuName': app.globalData.manuName
    },
    success: function (res) {
      if (res.data.code == 1200) {
        that.setData({
          like: !that.data.like
        });
        wx.showToast({
          title: res.data.content,
          icon: 'success',
          duration: 2000
        })
      } else {
        console.log(res.data.msg);
      }
    }
  })
}

//获取商品评价列表
function QueryCommentList(obj) {
  wx.showLoading({
    title: '加载中...',
    mask: true
  });

  var url = apiurl + '/mobile/api/Product/GetCommentList';

  wx.request({
    url: url,
    data: { "CustId": custId, "Id": obj.data.productId, "Status": Status, "PageIndex": PageIndex, "PageSize": PageSize, "IsMyComment": 1, UnionStoreID: obj.data.shopID },
    method: 'GET',
    header: {
      'content-type': 'application/json',
      'X_ManuName': app.globalData.manuName
    },
    success: function (res) {
      wx.hideLoading();
      if (res.data.content == null) {
        return false;
      }
      var dlist = obj.data.CommentList;
      var d = res.data.content.Data;
      for (var i = 0; i < d.length; i++) {
        dlist.push(d[i]);
      }
      obj.setData({
        CommentList: dlist
      })
      if (d.length != PageSize) {
        IsLastPage = true;
        return false;
      }
    },
    fail: function () {
      wx.hideLoading();
      wx.showToast({
        title: '获取评论列表失败',
        duration: 2000
      })
    },
    complete: function () {
      //complete
    }
  })
}

function loadUnionStore(that) {
  wx.request({
    url: app.globalData.apiurl + '/mobile/api/Unionstore/GetShopByID',
    data: { CustId: custId, UnionShopID: that.data.shopID },
    method: 'GET',
    header: {
      'X_ManuName': app.globalData.manuName
    },
    success: function (res) {

      if (res.data.code == 1200) {
        var result = res.data.content;
        that.setData({
          shopName: result.ShopName,
          imgUrls: "http://img4.winmobi.cn" + result.Logo
        });
      }
    }
  });

  wx.request({
    url: app.globalData.apiurl + '/mobile/api/Product/SumUnionStoreStock',
    data: { CustId: custId, UnionStoreID: that.data.shopID },
    method: 'GET',
    header: {
      'X_ManuName': app.globalData.manuName
    },
    success: function (res) {

      if (res.data.code == 1200) {
        var result = res.data.content;
        that.setData({
          StockNum: result.StockNum,
          SurplusStockNum: result.SurplusStockNum
        });
      }
    }
  });

  wx.request({
    url: app.globalData.apiurl + '/mobile/api/Product/CountUnionShopCollection',
    data: { CustId: custId, UnionStoreID: that.data.shopID },
    method: 'GET',
    header: {
      'X_ManuName': app.globalData.manuName
    },
    success: function (res) {

      if (res.data.code == 1200) {
        var result = res.data.content;
        that.setData({
          CollectionNum: result

        });
      }
    }
  });

}

